/**
 * 评论 API 处理器
 */
import { comments, users } from '../data/generator.js'

class CommentHandler {
  /**
   * 获取评论列表（支持分页和嵌套结构）
   */
  static getComments(query = {}) {
    const {
      articleId,
      page = 1,
      limit = 10,
      parentId = null,
      sort = 'createdAt',
      order = 'desc',
    } = query

    let filteredComments = [...comments]

    // 按文章ID过滤
    if (articleId) {
      filteredComments = filteredComments.filter((comment) => comment.articleId === articleId)
    }

    // 按父评论ID过滤（获取回复）
    if (parentId !== null) {
      filteredComments = filteredComments.filter((comment) => comment.parentId === parentId)
    } else {
      // 只获取顶级评论
      filteredComments = filteredComments.filter((comment) => !comment.parentId)
    }

    // 只显示已审核通过的评论
    filteredComments = filteredComments.filter((comment) => comment.status === 'approved')

    // 排序
    filteredComments.sort((a, b) => {
      const aValue = new Date(a.createdAt).getTime()
      const bValue = new Date(b.createdAt).getTime()
      return order === 'desc' ? bValue - aValue : aValue - bValue
    })

    // 分页
    const total = filteredComments.length
    const start = (page - 1) * limit
    const end = start + limit
    const data = filteredComments.slice(start, end)
    const totalPages = Math.ceil(total / limit)

    // 为每个评论添加回复数量
    const commentsWithReplyCount = data.map((comment) => {
      const replyCount = comments.filter(
        (c) => c.parentId === comment.id && c.status === 'approved',
      ).length
      return {
        ...comment,
        replyCount,
        likes: comment.likes || 0,
        isLiked: comment.isLiked || false,
      }
    })

    return {
      code: 200,
      message: 'success',
      data: commentsWithReplyCount,
      pagination: {
        page,
        limit,
        total,
        totalPages,
        hasNext: page < totalPages,
        hasPrev: page > 1,
      },
      timestamp: new Date().toISOString(),
    }
  }

  /**
   * 获取评论详情
   */
  static getCommentById(id) {
    const comment = comments.find((c) => c.id === id)

    if (!comment) {
      return {
        code: 404,
        message: '评论不存在',
        data: null,
      }
    }

    return {
      code: 200,
      message: 'success',
      data: comment,
    }
  }

  /**
   * 创建评论
   */
  static createComment(data) {
    const { articleId, content, parentId = null, authorId, mentionedUsers = [] } = data

    if (!articleId || !content || !authorId) {
      return {
        code: 400,
        message: '缺少必要参数',
        data: null,
      }
    }

    // 查找作者信息
    const author = users.find((u) => u.id === authorId)
    if (!author) {
      return {
        code: 400,
        message: '用户不存在',
        data: null,
      }
    }

    const newComment = {
      id: (Math.max(...comments.map((c) => parseInt(c.id))) + 1).toString(),
      articleId,
      content,
      parentId,
      author: {
        id: author.id,
        name: author.name || author.username,
        avatar: author.avatar,
        username: author.username,
      },
      mentionedUsers,
      likes: 0,
      isLiked: false,
      status: 'approved', // 默认审核通过
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    }

    comments.push(newComment)

    return {
      code: 200,
      message: 'success',
      data: newComment,
    }
  }

  /**
   * 更新评论
   */
  static updateComment(id, data) {
    const index = comments.findIndex((c) => c.id === id)

    if (index === -1) {
      return {
        code: 404,
        message: '评论不存在',
        data: null,
      }
    }

    comments[index] = {
      ...comments[index],
      ...data,
      id: comments[index].id, // 保持ID不变
      updatedAt: new Date().toISOString(),
    }

    return {
      code: 200,
      message: 'success',
      data: comments[index],
    }
  }

  /**
   * 删除评论
   */
  static deleteComment(id) {
    const index = comments.findIndex((c) => c.id === id)

    if (index === -1) {
      return {
        code: 404,
        message: '评论不存在',
        data: null,
      }
    }

    // 同时删除所有回复
    const replies = comments.filter((c) => c.parentId === id)
    replies.forEach((reply) => {
      const replyIndex = comments.findIndex((c) => c.id === reply.id)
      if (replyIndex !== -1) {
        comments.splice(replyIndex, 1)
      }
    })

    const deletedComment = comments.splice(index, 1)[0]

    return {
      code: 200,
      message: 'success',
      data: {
        id: deletedComment.id,
        content: deletedComment.content,
      },
    }
  }

  /**
   * 点赞/取消点赞评论
   */
  static toggleLike(id, userId) {
    const comment = comments.find((c) => c.id === id)

    if (!comment) {
      return {
        code: 404,
        message: '评论不存在',
        data: null,
      }
    }

    // 初始化点赞相关字段
    if (!comment.likes) comment.likes = 0
    if (!comment.likedUsers) comment.likedUsers = []

    const userIndex = comment.likedUsers.indexOf(userId)

    if (userIndex > -1) {
      // 取消点赞
      comment.likedUsers.splice(userIndex, 1)
      comment.likes--
      comment.isLiked = false
    } else {
      // 点赞
      comment.likedUsers.push(userId)
      comment.likes++
      comment.isLiked = true
    }

    comment.updatedAt = new Date().toISOString()

    return {
      code: 200,
      message: 'success',
      data: {
        id: comment.id,
        likes: comment.likes,
        isLiked: comment.isLiked,
      },
    }
  }

  /**
   * 获取评论的回复列表
   */
  static getReplies(parentId, query = {}) {
    const { page = 1, limit = 5 } = query

    const replies = comments.filter((c) => c.parentId === parentId && c.status === 'approved')

    // 按时间排序
    replies.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())

    // 分页
    const total = replies.length
    const start = (page - 1) * limit
    const end = start + limit
    const data = replies.slice(start, end)
    const totalPages = Math.ceil(total / limit)

    return {
      code: 200,
      message: 'success',
      data,
      pagination: {
        page,
        limit,
        total,
        totalPages,
        hasNext: page < totalPages,
        hasPrev: page > 1,
      },
    }
  }

  /**
   * 搜索用户（用于@功能）
   */
  static searchUsers(query = {}) {
    const { q = '', limit = 10 } = query

    if (!q.trim()) {
      return {
        code: 200,
        message: 'success',
        data: users.slice(0, limit),
      }
    }

    const filteredUsers = users
      .filter(
        (user) =>
          user.name?.toLowerCase().includes(q.toLowerCase()) ||
          user.username?.toLowerCase().includes(q.toLowerCase()),
      )
      .slice(0, limit)

    return {
      code: 200,
      message: 'success',
      data: filteredUsers,
    }
  }

  /**
   * 获取评论统计信息
   */
  static getCommentStats(articleId) {
    const articleComments = comments.filter(
      (c) => c.articleId === articleId && c.status === 'approved',
    )
    const totalComments = articleComments.length
    const totalReplies = comments.filter(
      (c) => articleComments.some((ac) => ac.id === c.parentId) && c.status === 'approved',
    ).length

    return {
      code: 200,
      message: 'success',
      data: {
        totalComments,
        totalReplies,
        totalInteractions: totalComments + totalReplies,
      },
    }
  }
}

export default CommentHandler
